package org.jash.shop2112.product

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import org.jash.shop2112.entity.Goods
import org.jash.shop2112.mvvm.BaseViewModel

class DetailViewModel:BaseViewModel() {
    val goodsLiveData by lazy { MutableLiveData<Goods>() }
    val addCartLiveData by lazy { MutableLiveData<String>() }
    fun loadGoods(id:Int) {
        viewModelScope.launch {
            try {
                val res = service.getGoodsDetail(id)
                if (res.code == 200) {
                    goodsLiveData.postValue(res.data)
                } else {
                    errorLiveData.postValue(RuntimeException(res.message))
                }
            } catch (e:Exception) {
                errorLiveData.postValue(e)
            }
        }
    }
   fun addCart(id:Int) {
        viewModelScope.launch {
            try {
                val res = service.addCart(mapOf("count" to "1", "goods_id" to id.toString()))
                if (res.code == 200) {
                    addCartLiveData.postValue(res.message)
                } else {
                    errorLiveData.postValue(RuntimeException(res.message))
                }
            } catch (e:Exception) {
                errorLiveData.postValue(e)
            }
        }
    }

}